package net.organizer.ui.actionhandler;

import java.util.List;
import java.util.logging.Logger;

import javax.servlet.http.HttpServletRequest;

import net.organizer.dao.Domain;
import net.organizer.dao.Org;

import org.json.JSONArray;
import org.json.JSONObject;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;

public class OrgGetListActionHandler extends ActionHandlerBase {
	private static final Logger logger = Logger.getLogger(OrgGetListActionHandler.class.getName());
	
	@Override
	public void handleAction(HttpServletRequest req, JSONObject respJSONObject) throws Exception {
		logger.fine("handleAction");
		Objectify ofy = ObjectifyService.begin();
		List<Org> orgs = ofy.query(Org.class).ancestor(Domain.getKey("domain1")).order("name").list();
		
		JSONArray  jSONArray = new JSONArray();
		for(Org org : orgs){
			logger.fine(String.format("org from db: %s", org));
			Key<Org> parentOrgKey = org.getParentOrgKey();
			logger.fine(String.format("parent org key: %s", parentOrgKey));
			if(parentOrgKey != null){
				Org parentOrg = ofy.get(parentOrgKey);
				org.setParentOrg(parentOrg);
			}
			jSONArray.put(org.toJSONObject());
		}
		respJSONObject.put("orgs", jSONArray);
	}
}
